var fs = require("fs");
var path = require("path");

var ffmpeg = require('ffmpeg');
var video2image = function (params, Callback) {

    var video_image_path = path.join(params.cache, 'video-image');

    var imagefile = path.join(video_image_path, params.id + "_v_1" + ".jpg");

    fs.exists(imagefile, function (err) {
        if (!err) {
            fs.exists(params.OriginalFile, function (err) {
                if (err) {
                    try {
                        var process = new ffmpeg(params.OriginalFile);
                        process.then(function (video) {

                            var len = video.metadata.duration.seconds;
                            video.fnExtractFrameToJPG(video_image_path, {
                                start_time: len < 5 ? 1 : 5,
                                frame_rate: 1,
                                number: 1,
                                file_name: params.id + "_v"
                            }, function (error, files) {
                                if (!error) {
                                    Callback(null, {
                                        path: imagefile
                                    })
                                } else {
                                    Callback(error)
                                }
                            });
                        }, function (error) {
                            ///   console.log('Error: ' + err);
                            Callback(error)
                        });
                    } catch (e) {
                        ///  console.log(e.code);

                        //  console.log(e);
                        // console.log(e.msg);
                        Callback(e)
                    }

                } else {
                    Callback({})
                }
            })
        } else {
            Callback(null, {
                path: imagefile
            })
        }

    })
}
module.exports = video2image;